package com.eage.security.filter;

import com.eage.security.utils.ShiroThreadLocalMap;
import com.eage.security.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: lex
 * @Date: 2019/2/27
 * @Desc 重写为授权下跳转的界面 原本shiro控制器跳转,ShiroFilterFactoryBean.setUnauthorizedUrl  因为是会重定向,所以重写方法.改为直接传输json
 * 执行顺序为isAccessAllowed 判断是否需要授权框架(ShiroFilterFactoryBean 里面设置的perms/roles) =>realm里面授权 给权限/角色 => onAccessDenied 没有权限则跳转
 * tip:onAccessDenied权限判断 同样会判断是否登入,所以不仅要重写无权限跳转saveRequestAndRedirectToLogin,还要重写无登入跳转saveRequestAndRedirectToNoAuth
 */
@Slf4j
public class NoRolesFilter extends RolesAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            log.error("该用户在访问受角色保护资源时候未登入");
            ShiroURLFunction.saveRequestAndRedirectToLogin(request, response);
        } else {
            HttpServletRequest httpServletRequest= (HttpServletRequest) request;
            log.error("用户:[ {} ] 没有访问该角色资源 [ {} ]",ShiroUtils.getUser().getUsername(),httpServletRequest.getRequestURI());
            ShiroThreadLocalMap.put("noAuthError", new StringBuilder().append("用户:[ ")
                    .append(ShiroUtils.getUser().getUsername()).append(" ]")
                    .append("没有访问该角色资源 [ ").append(httpServletRequest.getRequestURI()).append(" ]"));
            ShiroURLFunction.saveRequestAndRedirectToNoAuth(request, response);
        }
        return false;
    }
}
